<template>
  <div class="app-container">
    <el-button
      type="primary"
      icon="el-icon-shopping-cart-full"
      @click="save"
      round
      >保存</el-button
    >
    <el-button
      type="danger"
      style="margin-left: 10px"
      icon="el-icon-back"
      @click="onCancel"
      round
      >返回</el-button>
    <el-table
      :data="treeNodeList"
      style="width: 100%; margin-bottom: 20px"
      v-loading="listLoading"
      element-loading-text="Loading"
      row-key="node.id"
      highlight-current-row
      default-expand-all
      @select="select"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" label="选择"></el-table-column>
      <el-table-column prop="node.title" label="菜单名称"></el-table-column>
      <el-table-column prop="node.path" label="路径"></el-table-column>
      <el-table-column label="是否隐藏页（用于子页面）">
        <template slot-scope="scope">
          {{ scope.row.node.hidden ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="按钮">
        <template slot-scope="scope">
          <div class="btns">
            <el-checkbox
              v-for="btn in scope.row.node.btns"
              :key="btn.txt"
              @change="preChange(scope.row, btn)"
              v-model="btn.checked"
              >{{ btn.txt }}</el-checkbox
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { selectByRole2Menu, saveRole2Menu } from '@/api/users'

@Component({
  name: 'role2menu'
})
export default class extends Vue {
  private listLoading: boolean = true
  created() {
    this.menu()
  }
  /**
   * 返回按钮
   */
    private onCancel() {
    this.$router.go(-1)
  }
  /**
   * 保存权限
   */
  private async save() {
    var menus = this.selectedLs.map((n: any) => {
      var btns = (n.node.btns || []).filter((it: any) => it.checked)
      var menu: any = { menuid: n.node.id, roleid: this.roleid }
      if (btns && btns.length > 0) {
        menu.btns = JSON.stringify(btns)
      }
      return menu
    })
    if (menus.length != 0) {
      const { data } = await saveRole2Menu(menus)
      this.$alert('操作成功！');
      setTimeout(() => {
          this.onCancel();
      }, 1000);
      //this.$alert(data.msg, '系统提示')
    }
  }
  private selectedItem() {
    var fn = (it: any) => {
      if (it.node.roleid) {
        ;(<any>this.$refs.multipleTable).toggleRowSelection(it, true)
      }
      if (it.children && it.children.length > 0) {
        this.treeVictor(it.children, fn)
      }
    }
    this.treeVictor(this.treeNodeList, fn)
  }
  private checkbox_change(node: any) {
    console.log(node)
  }
  /**
   * 点击权限按钮
   */
  private preChange(node: any, btn: any) {
    if (btn.checked) {
      ;(<any>this.$refs.multipleTable).toggleRowSelection(node, true)
    } else {
      var f = false
      ;(node.node.btns || []).forEach((n: any) => {
        if (n.checked) f = true
      })
      if (!f) {
        ;(<any>this.$refs.multipleTable).toggleRowSelection(node, false)
      }
    }
  }
  //选中的行
  private selectedLs = []
  private handleSelectionChange(selection: any, row: any) {
    this.selectedLs = selection
  }
  /**
   * 单击行checkbox事件
   */
  private select(selection: any, row: any) {
    //以此判断当前是选中还是取消 大于0当前状态是选中，小于0当前状态是取消
    var indx = selection.indexOf(row)
    //选中子节点
    if (row.children) {
      row.children.forEach((it: any) => {
        ;(<any>this.$refs.multipleTable).toggleRowSelection(it, indx > -1)
      })
    }
    //console.log(row.parentNode?.node?.id);
    //寻找上级节点
    var node: any = {}
    if (row.parentNode && row.parentNode.node) {
      var pid = row.parentNode.node.id

      var fn = (it: any) => {
        if (it.node.id == pid) {
          node = it
        }
        if (it.children) {
          var v: any = this.treeVictor(it.children, fn)
          if (v) {
            node = v
            return
          }
        }
      }
      this.treeVictor(this.treeNodeList, fn)
      //如果是子节点就选中上级目录
      if (node && indx > -1) {
        ;(<any>this.$refs.multipleTable).toggleRowSelection(node, true)
      }
    }
    //取消父级节点
    if (indx == -1 && node) {
      if (node.children) {
        var find = false
        node.children.forEach((n: any) => {
          if (selection.includes(n)) {
            find = true
          }
        })
        if (!find) {
          ;(<any>this.$refs.multipleTable).toggleRowSelection(node, false)
        }
      }
    }
  }
  private treeNodeList = []
  private roleid = this.$route.query.id

  private async menu() {
    const { data } = await selectByRole2Menu({ roleid: this.roleid })

    var fn = (it: any) => {
      if (it.node.btns) {
        it.node.btns = eval('(' + it.node.btns + ')')
      }

      var o: any = {}
      if (it.node.perbtns) {
        it.node.perbtns = eval('(' + it.node.perbtns + ')')

        it.node.perbtns.forEach((btn: any) => {
          o[btn.txt] = 1
        })
      }
      if (it.node.btns && it.node.btns.length > 0) {
        it.node.btns.forEach((it: any) => {
          it.checked = !!o[it.txt]
        })
      }

      if (it.children && it.children.length > 0) {
        this.treeVictor(it.children, fn)
      }
    }
    this.treeVictor(data, fn)

    this.treeNodeList = data
    setTimeout(() => {
      this.selectedItem()
    }, 500)
    this.listLoading = false
  }
  treeVictor(data: any, fn: Function) {
    data.forEach((it: any) => {
      fn(it)
    })
  }
}
</script>
